/*
 * @Author: your name
 * @Date: 2020-06-02 14:50:03
 * @LastEditTime: 2020-06-03 16:05:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \GW-Single\main\internet\ethernet_app.c
 */ 
/* ethernet Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_system.h"
#include "esp_err.h"
#include "esp_event_loop.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_eth.h"

#include "esp32/rom/gpio.h"

#include "tcpip_adapter.h"
#include "driver/gpio.h"
#include "driver/periph_ctrl.h"

#include "internet_common.h"


#include "esp_eth_phy.h"

#define PIN_SMI_MDC 23
#define PIN_SMI_MDIO 18

static const char *TAG = "eth";

const int CONNECTED_BIT = IPV4_GOTIP_BIT;


int ethernet_init(void* args)
{
    // tcpip_adapter_init();

    // ESP_ERROR_CHECK(esp_event_loop_init(eth_event_handler, NULL));

    static bool eth_initialized = false;
    if(eth_initialized == false)
    {
        ESP_LOGI("ETH-INIT","INTO ethernet init");

        eth_config_t config = DEFAULT_ETHERNET_PHY_CONFIG;
        config.phy_addr = PHY1;
        config.gpio_config = eth_gpio_config_rmii;
        config.tcpip_input = tcpip_adapter_eth_input;
        config.clock_mode = ETH_CLOCK_GPIO17_OUT;
    #ifdef CONFIG_PHY_USE_POWER_PIN
        /* Replace the default 'power enable' function with an example-specific one
        that toggles a power GPIO. */
        config.phy_power_enable = phy_device_power_enable_via_gpio;
    #endif

        ESP_ERROR_CHECK(esp_eth_init(&config));
    
        eth_initialized = true;
    }

    ESP_ERROR_CHECK(esp_eth_enable()) ;

    ESP_LOGI(TAG,"Trying Ethernet Connecting...");

    xEventGroupClearBits(ethernet_event_group, CONNECTED_BIT);
    xEventGroupWaitBits(ethernet_event_group, CONNECTED_BIT,1, 1, 10000 / portTICK_PERIOD_MS);//10s超时，连不上则表明以太网无法上网

    return isEthernetConnected();
}